/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ControllerAjax;

import GestionBDD.ControllerBDD;
import Main.StaticParams;
import Model.Roles;
import Model.Utilisateur;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.Principal;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author bello
 */
@WebServlet(name = "ControllerUser", urlPatterns = {"/User/*"})
public class ControllerUser extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo =  request.getPathInfo();
        if(pathInfo.equals("/connect"))
        {
            Utilisateur u = this.getUserFromName(request.getUserPrincipal().getName());
            boolean admin = false;
            for(Roles r : u.getRolesList())
            {
                if(r.getRole().equals(StaticParams.ADMIN_ROLE))
                {
                    admin = true;
                }
            }
            request.getSession(true).setAttribute("userIsAdmin", admin);
            response.sendRedirect(getServletContext().getContextPath() + "/index.jsp");
        }
        if(pathInfo.equals("/add"))
        {
            String nom = request.getParameter("nom");
            String prenom = request.getParameter("prenom");
            String password = request.getParameter("j_password");
            String role = request.getParameter("role");
            

            if((nom != null) && (prenom != null) && (password != null) && (role!=null))
            {
                String login = nom + "." + prenom;
                Utilisateur u = new Utilisateur();
                u.setNom(nom);
                u.setPrenom(prenom);
                u.setLogin(login);
                u.setPassword(this.passwordEncoder(password));
                
                Roles r = new Roles();
                r.setRole(role);
                r.setLogin(login);
                r.setUtilisateuridUtilisateur(u);
                u.getRolesList().add(r);
                
                List<Utilisateur> lu = (List<Utilisateur>) getServletContext().getAttribute("users");
                lu.add(u);
                ControllerBDD.getINSTANCE().add(u);
                ControllerBDD.getINSTANCE().add(r);
                
                request.getSession(true).setAttribute("user", u);
            }
            response.sendRedirect(getServletContext().getContextPath() + "/index.jsp");
        }
        else if(pathInfo.equals("/logout"))
        {
            Principal userPrincipal = request.getUserPrincipal();

            if(userPrincipal != null) 
            {
                System.out.println("Principal found");
                request.getSession().invalidate();
            }
            response.sendRedirect(getServletContext().getContextPath());
        }
    }
    
    public Utilisateur getUserFromId(int id)
    {
        List<Utilisateur> lu = (List<Utilisateur>)getServletContext().getAttribute("users");
        
        for(Utilisateur u : lu)
        {
            if(u.getIdUtilisateur() == id)
            {
                return u;
            }
        }
        return null;
    }
    
    public Utilisateur getUserFromName(String name)
    {
        List<Utilisateur> lu = (List<Utilisateur>)getServletContext().getAttribute("users");
        
        for(Utilisateur u : lu)
        {
            if(u.getLogin().equals(name))
            {
                return u;
            }
        }
        return null;
    }
        
    public String decode(byte[] hash) {  
        StringBuilder sb = new StringBuilder(); 
        for (int i = 0; i < hash.length; i++) {  
            int v = hash[i] & 0xFF; 
            if(v < 16) {
                sb.append("0"); 
            }
            sb.append(Integer.toString(v, 16)); 
        }  
        return sb.toString();
    }
    
    public String passwordEncoder(String plainText) {
        MessageDigest digest;
        try {
            digest = MessageDigest.getInstance("SHA-256");
            digest.reset();

            byte rawPassword[] = digest.digest(plainText.getBytes("UTF-8"));
            return decode(rawPassword);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
